<template>
    <div id="ve_20210421_1243" class="ve_20210421_1243">
      <!--校验-->
      <a-modal
        :open="checkInfos.visible"
        :title="$t('preCheck.verifyLog.title')"
        :mask-closable="false"
        width="85%"
        @cancel="checkInfosCancel"
      >
        <!-- {{ checkInfos }} -->
        <a-card
          :loading="checkInfos.loading"
          :element-loading-text="checkInfos.loadingText"
          element-loading-spinner="el-icon-loading"
          v-if="checkInfos.visible"
          class="box-card flex-none"
          style="height: 100%; flex: 1; display: flex; flex-direction: column"
          :title="$t('preCheck.verifyLog.cardTitle')"
        >
          <a-row style="margin-top: 10px">
            <a-progress
              :percent="checkInfos.percentage"
              :stroke-width="20"
              :text-inside="true"
            ></a-progress>
          </a-row>
          <div style="width: 100%; height: 85%; display: flex; margin-top: 30px">
            <a-card
              class="j_msg"
              style="
                width: 90%;
                height: 100%;
                flex: 1;
                margin-right: 20px !important;
              "
              :title="$t('preCheck.verifyLog.cardTitle')"
            >
              <!-- {{ checkInfos.infos }} -->
              <a-timeline>
                <a-timeline-item
                  v-for="(activity, index) in checkInfos.infos"
                  :key="index"
                  :color="activity.color"
                >
                  <p>{{ activity.content }}</p>
                  <p style="color: #ccc">{{ activity.timestamp }}</p>
                </a-timeline-item>
              </a-timeline>
            </a-card>
            <a-card
              class="j_msg_2"
              style="width: 100%; height: 100%; flex: 1; overflow: auto"
            >
              <!-- {{ cmdscheckInfos }} -->
              <custom
                style="height: 100%; flex: 1"
                :datamsg="cmdscheckInfos"
              ></custom>
            </a-card>
          </div>
        </a-card>
        <template #footer>
          <a-button size="small" @click="checkInfosCancel">{{$t('preCheck.verifyLog.close')}}</a-button>
        </template>
      </a-modal>
    </div>
  </template>
  
  <script setup>
  import { reactive, ref, h, defineEmits, inject } from "vue";
  import * as http from "@/api/flow/createTask";
  import * as http2 from "@/api/index";
  import custom from "./customCmd.vue";
  import { Modal, message } from "ant-design-vue";
  import { createOpen } from "@/store/modules/createOpen";
  import { useStore } from "vuex";
  import emiter from "@/plugins/bus.js";
  const store = useStore();
  const closeDrawer = inject('closeDrawer');
  const checkInfos = ref({
    loading: false,
    loadingText: "",
    visible: false,
    title: "",
    stat: false, // false未激活 true激活
    index: 0, // 存储轮序 索引
    percentage: 50,
    customColors: [
      { color: "#f56c6c", percentage: 20 },
      { color: "#e6a23c", percentage: 40 },
      { color: "#409eff", percentage: 60 },
      { color: "#5cb87a", percentage: 80 },
      { color: "#5cb87a", percentage: 100 },
    ],
    infos: [
      {
        content: $t('preCheck.verifyLog.baseConfig'),
        timestamp: "2018-04-12 20:46",
        size: "large",
        color: "#3ebd1c",
        icon: "el-icon-success",
      },
      {
        content: $t('preCheck.verifyLog.upload'),
        timestamp: "2018-04-12 20:46",
        size: "large",
        color: "#bd1a0e",
        icon: "el-icon-error",
      },
    ],
  });
  const cmdscheckInfos = reactive({
    isrefresh: false, // 刷新 title-edit
    isrefresh2: false, // 刷新 edit-title
    top: false, // 到达顶部标记
    bottom: false, // 到达顶部标记
    msg: "",
    edit: false, // 可编辑
  });
  const checkType = ref(1);           //校验类型：1->创建时部署，2->查看任务时保存
  // const checkInfosCancel = () => {
  //   checkInfos.value.visible = false;
  // };
  
  const checkInfosOpen = () => {
    console.log(cmdscheckInfos.isrefresh2, "cmdscheckInfos");
    checkInfos.value.percentage = 0;
    checkInfos.value.infos = [];
    cmdscheckInfos.msg = $t('preCheck.verifyLog.noInfo');
    cmdscheckInfos.bottom = !cmdscheckInfos.bottom;
    checkInfos.value.title = $t('preCheck.verifyLog.title');
    checkInfos.value.visible = true;
    checkInfosDo();
  
    checkInfos.value.index = setInterval(() => {
        console.log(checkInfos.value.index, "checkInfos.value.index");
      checkInfosIng();
    }, 1000);
  };
  // 采集任务
  const startFlow = async () => {
    await http2.startFlow({ flowId: store.state.taskInfo.flowId })
  };
  const checkInfosDo = async () => {
    let params = {
      flowId:  store.state.taskInfo.flowId,
      isUpload: 1, //-1 不上传 1 上传
      isConfig: 1, //-1不注册  1注册
    }

    const response = await http.startAuto(params);
  
    // 清除轮询
    clearInterval(checkInfos.value.index);
    setTimeout(() => {
      clearInterval(checkInfos.value.index);
      checkInfos.value.index = 0;
      if (response.code) {
        
        checkInfosIng(checkType.value);
      }
    }, 1000);
    if (response.code == true) {
    }
  };
  // 后端说编辑的时候再调用一次，isupload改成-1
  const savaIsEditMode = async () => {
    let params = {
      flowId:  store.state.taskInfo.flowId,
      isUpload: -1, //-1 不上传 1 上传
      isConfig: 1, //-1不注册  1注册
    }
  await http.startAuto(params);

  };
  /* 
  
   * 轮询
   * @param {*} type 1:创建任务->部署 
   *                 2:查看任务->保存
  */
  const checkInfosIng = async (type) => {
    //   let ids = verifyMsg.vmsg
    let ids = "";
    let isRegister = true;
    let isETL = true;
    // 其他逻辑...
    var params = {
      flowId: store.state.taskInfo.flowId,
    };
  
    let response = await http.totalCheck(params);
    console.log(response, "response");
    if (response.code == "000000") {
      const ars = response?.data?.dataInfo || [];
      const infos = ref([]);
      const color1 = ["#bd1a0e", "#0685cc", "#3ebd1c"];
      const color2 = ["el-icon-error", "el-icon-loading", "el-icon-success"];
      const color3 = [
        $t('preCheck.verifyLog.fail'),
        $t('preCheck.verifyLog.processing'),
        $t('preCheck.verifyLog.success')
      ];
  
      ars.forEach((item) => {
        infos.value.push({
          content: item.name,
          timestamp: $t('preCheck.verifyLog.status') + color3[item.check + 1],
          size: "large",
          color: color1[item.check + 1],
          icon: color2[item.check + 1],
        });
      });
      if (parseFloat(response.data.percent) > checkInfos.value.percentage) {
        checkInfos.value.percentage = parseFloat(response.data.percent);
      }else if(parseFloat(response.data.percent) == 0){
        message.error($t('preCheck.verifyLog.deployFail'));
        checkInfos.value.percentage = 0
      }
  
      checkInfos.value.infos = infos.value;
      console.log(cmdscheckInfos, "cmdscheckInfos");
      console.log(type, "type");
      console.log(response.data.Info, "response.data.Info");
      console.log(checkInfos.value.percentage, "checkInfos.value.percentage");
      cmdscheckInfos.msg = response.data.Info.replace(/\n/g, "<br>");
  
      // nextTick(() => {
      cmdscheckInfos.bottom = !cmdscheckInfos.bottom;
      // 创建任务
      if (type == 1&&checkInfos.value.percentage >= 100) {
        Modal.confirm({
          title: $t('preCheck.verifyLog.tip'),
          content: h('div', null, [
            h('p', null, $t('preCheck.verifyLog.deployDone')),
            h('p', { style: 'color: #ccc;' }, $t('preCheck.verifyLog.deployDone1'))
          ]),
          okText: $t('preCheck.verifyLog.ok'),
          cancelText: $t('preCheck.verifyLog.cancel'),
          type: "warning",
          onOk: () => {
            return new Promise((resolve, reject) => {
              setTimeout(()=>{
                  // 开始采集任务
                  startFlow()
                  resolve()
                  close()
                  closeDrawer()
                  createOpen().changeOpen(false);
                  checkInfos.value.visible = false;
              }, 1000);
            }).catch(() => 
            {
              checkInfos.value.visible = false
              console.log("Oops errors!")
            });
            // emit event to parent component if needed
          },
          onCancel: () => {
            emit('close');
            closeDrawer()
            createOpen().changeOpen(false);
            checkInfos.value.visible = false;
          },
        });
      }
      // 查看任务二次校验
      if (type == 2) {
        checkInfos.value.percentage = 100;

        Modal.confirm({
          title: $t('preCheck.verifyLog.tip'),
          content: h('div', null, [
            h('p', null, $t('preCheck.verifyLog.updateDone')),
            h('p', { style: 'color: #ccc;' }, $t('preCheck.verifyLog.updateDesc'))
          ]),
          okText: $t('preCheck.verifyLog.ok'),
          cancelText: $t('preCheck.verifyLog.cancel'),
          type: "warning",
          onOk: () => {
            return new Promise((resolve, reject) => {
              setTimeout(()=>{
                  resolve()
                  close()
              }, 1000);
            }).catch(() => console.log("Oops errors!"));
            // emit event to parent component if needed
          },
          onCancel: () => {},
        });
      }
      // });
    }
  };
  const close = () => {
    checkInfos.value.visible = false;
    emit('close')
  };
  const checkInfosCancel = (param, params3) => {
    console.log("11111111");
    checkInfos.value.visible = false;
    // 清除轮询
    clearInterval(checkInfos.value.index);
    setTimeout(() => {
      clearInterval(checkInfos.value.index);
      checkInfos.value.index = 0;
    }, 1000);
    console.log(checkInfos.value.visible);
    //   emit("close:open")
  };
  
  const openModel = (type = 1) => {
    checkInfos.value.visible = true;
    checkType.value = type
    checkInfosOpen();
  };
  
  defineExpose({ openModel });
  const emit = defineEmits(['close'])
  </script>
  